package com.easyctba.core.service.impl;

import cn.hutool.core.io.file.PathUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.easyctba.common.core.domain.R;
import com.easyctba.common.core.utils.MapstructUtils;
import com.easyctba.common.core.utils.StringUtils;
import com.easyctba.common.core.utils.file.FileUtils;
import com.easyctba.common.mybatis.core.page.TableDataInfo;
import com.easyctba.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.easyctba.core.algorithm.exec.StExec;
import com.easyctba.core.domain.CtbaEntropy;
import com.easyctba.core.domain.CtbaFias;
import com.easyctba.core.domain.bo.StConfigBo;
import com.easyctba.core.domain.bo.StEncodeBo;
import com.easyctba.core.domain.vo.CtbaFiasVo;
import com.easyctba.core.enums.EntropyStatus;
import com.easyctba.core.enums.StStatus;
import com.easyctba.core.util.FileUtil;
import com.easyctba.resource.api.RemoteFileService;
import com.easyctba.resource.api.domain.RemoteFile;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import com.easyctba.core.domain.bo.CtbaStBo;
import com.easyctba.core.domain.vo.CtbaStVo;
import com.easyctba.core.domain.CtbaSt;
import com.easyctba.core.mapper.CtbaStMapper;
import com.easyctba.core.service.ICtbaStService;
import org.springframework.util.StopWatch;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * st分析Service业务层处理
 *
 * @author LionLi
 * @date 2024-02-28
 */
@RequiredArgsConstructor
@Service
public class CtbaStServiceImpl implements ICtbaStService {

    private final CtbaStMapper baseMapper;

    @DubboReference
    private RemoteFileService remoteFileService;

    /**
     * 查询st分析
     */
    @Override
    public CtbaStVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询st分析列表
     */
    @Override
    public TableDataInfo<CtbaStVo> queryPageList(CtbaStBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CtbaSt> lqw = buildQueryWrapper(bo);
        Page<CtbaStVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询st分析列表
     */
    @Override
    public List<CtbaStVo> queryList(CtbaStBo bo) {
        LambdaQueryWrapper<CtbaSt> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CtbaSt> buildQueryWrapper(CtbaStBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CtbaSt> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getProjectId() != null, CtbaSt::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getStStatus()), CtbaSt::getStStatus, bo.getStStatus());
        return lqw;
    }

    /**
     * 新增st分析
     */
    @Override
    public Boolean insertByBo(CtbaStBo bo) {
        CtbaSt add = MapstructUtils.convert(bo, CtbaSt.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改st分析
     */
    @Override
    public Boolean updateByBo(CtbaStBo bo) {
        CtbaSt update = MapstructUtils.convert(bo, CtbaSt.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CtbaSt entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除st分析
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<CtbaStVo> getInfoByUserAndProject(Long id) {
        LambdaQueryWrapper<CtbaSt> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CtbaSt::getProjectId,id);
        CtbaStVo ctbaStVo = baseMapper.selectVoOne(wrapper);
        return R.ok(ctbaStVo);
    }
    /**
     * 创建项目时初始化信息熵分析表
     * @param projectId 项目id
     * @return 是否成功
     */
    @Override
    public Boolean initST(Long projectId) {
        //设置项目id和st_status为upload
        CtbaSt ctbaSt=new CtbaSt();
        ctbaSt.setStStatus(StStatus.upload);
        ctbaSt.setProjectId(projectId);
        return baseMapper.insert(ctbaSt)>0;
    }

    //上传视频的更新函数
    @Override
    public Boolean sTUploadVideo(Long id, String url) {
        CtbaSt ctbaSt = baseMapper.selectById(id);
        ctbaSt.setVideoUrl(url);
        return baseMapper.updateById(ctbaSt)>0;
    }

    /**
     * 更新视频封面
     * @param ossId 对象存储id
     * @return 是否成功
     */
    @Override
    public Boolean updateCover(Long ossId,Long id) {
        CtbaSt ctbaSt = baseMapper.selectById(id);
        ctbaSt.setCover(ossId);
        return baseMapper.updateById(ctbaSt)>0;
    }

    @Override
    public R<Void> stConfig(StConfigBo bo) {
        Long id = bo.getId();
        CtbaSt ctbaSt = baseMapper.selectById(id);
        ctbaSt.setDuration(bo.getDuration());
        ctbaSt.setInterval(bo.getInterval());
        ctbaSt.setEndTime(bo.getEndTime());
        ctbaSt.setStartTime(bo.getStartTime());
        //更新状态
        ctbaSt.setStStatus(StStatus.encode);
        boolean b=baseMapper.updateById(ctbaSt)>0;
        return b?R.ok():R.fail("更新ST分析状态失败");
    }

    @Override
    public R<Void> encode(StEncodeBo bo,Long id) {
        var stopWatch = new StopWatch();
        stopWatch.start();

        //生成st表
        StExec stExec = new StExec();
        CtbaSt ctbaSt = baseMapper.selectById(id);
        Long interval = ctbaSt.getInterval();
        String path = stExec.stTable(bo.getCodeList(),interval,ctbaSt.getId());
        //上传st表
        File file = cn.hutool.core.io.FileUtil.file(path);
        String name = file.getName();
        var fileUtil = new FileUtil();
        byte[] fileBytes;
        try {
            fileBytes = fileUtil.file2ByteArray(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        RemoteFile upload = remoteFileService.upload(name, name, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileBytes);
        Double rt = stExec.rt(bo.getCodeList()); //rt值
        Double ch = stExec.ch(bo.getCodeList()); //ch值
        String mode = stExec.mode(rt, ch); //教学模式
        //保存信息
        Long ossId = upload.getOssId();
        ctbaSt.setStStatus(StStatus.result);
        ctbaSt.setCodeTable(ossId);
        ctbaSt.setCh(ch);
        ctbaSt.setRt(rt);
        ctbaSt.setMode(mode);

        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        ctbaSt.setTime(totalTimeMillis);
        baseMapper.updateById(ctbaSt);
        return R.ok();
    }

    @Override
    public R<Void> pre(Long id) {
        CtbaSt ctbaSt = baseMapper.selectById(id);
        ctbaSt.setStStatus(StStatus.encode);
        return baseMapper.updateById(ctbaSt)==1 ? R.ok() : R.fail("返回上一步失败");
    }

    @Override
    public R<Void> finish(Long id) {
        CtbaSt ctbaSt = baseMapper.selectById(id);
        ctbaSt.setStStatus(StStatus.download);
        return baseMapper.updateById(ctbaSt)>=1?R.ok() : R.fail("更新状态失败");
    }
}
